import random
import string
from datetime import datetime
from importlib import import_module
from time import time

from flask import Flask, g

from app.extensions import api, redis
from app.routes import routes


def configure_blueprint(app):
    """ 注册初始化blueprint """
    for blueprint, url_prefix in routes:
        app.register_blueprint(blueprint, url_prefix=url_prefix)


def load_config_class(config_name):
    """ 导入配置文件 """
    config_class_name = '%sConfig' % config_name.capitalize()
    mod = import_module('config')
    config_class = getattr(mod, config_class_name)
    return config_class


def configure_context_processors(app):
    """ 配置上下文 """

    @app.before_request
    def before_request():
        g.now_timestamp = time()
        g.now = datetime.now()
        g.rand_str = ''.join(random.sample(string.ascii_letters + string.digits, 10))

    @app.after_request
    def make_session_permanent(response):
        print(response.status, flush=True)
        return response


def create_app(config_name):
    app = Flask(__name__)

    config_class = load_config_class(config_name)
    app.config.from_object(config_class)

    api.init_app(app)
    redis.init_app(app)
    configure_blueprint(app)

    configure_context_processors(app)
    return app
